package br.com.neb.caronamanager.view;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import br.com.neb.caronamanager.R;
import br.com.neb.caronamanager.adapter.CaronaAdapter;
import br.com.neb.caronamanager.model.Carona;
import br.com.neb.caronamanager.model.dao.DB;

public class CaronaFragment extends Fragment{
	
	
	private static CaronaFragment instance;
	private DB db;
	
	public static CaronaFragment getInstance(){
		return instance;
	}
	
	private CaronaAdapter adapter;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View caronaView = inflater.inflate(R.layout.fragment_carona, container,false);
		instance = this;
		db = new DB(caronaView.getContext());
		
		List<Carona> itemList = db.search();
		
		adapter = new CaronaAdapter(itemList, caronaView.getContext());
		
		final ListView listview = (ListView)caronaView.findViewById(R.id.list_caronas);
		listview.setAdapter(adapter);
		
		Button btn = (Button)caronaView.findViewById(R.id.btnShowDate);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DatePicker dp = (DatePicker)caronaView.findViewById(R.id.myDatePicker);
				String timeString = String.valueOf((dp.getCalendarView().getDate()/1000));
				Integer date = Integer.valueOf(timeString);
				db.insert(new Carona(date,UUID.randomUUID().toString().substring(0, 5),1));
				adapter.getData().clear();
				adapter.getData().addAll(db.search());
				adapter.notifyDataSetChanged();
				
				Toast t = Toast.makeText(caronaView.getContext(), "Carona inserida com sucesso!", Toast.LENGTH_SHORT);
				t.show();
			}
		});
		
		return caronaView;
	}
	
	public void delete(Carona carona){
		db.delete(carona);
		adapter.getData().clear();
		adapter.getData().addAll(db.search());
		adapter.notifyDataSetChanged();
	}

}
